package com.cndw.kungfu.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.kungfu.comm.LocalCommand;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsDailyItem;
import com.cndw.kungfu.config.ConstantsDayIntKey;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.CrossProxySerialize;
import com.cndw.kungfu.model.DataSerialize;
import com.cndw.kungfu.model.WarCrossAreaSerialize;
import com.cndw.kungfu.model.business.IPlayerManager;
import com.cndw.kungfu.model.pvp.api.ApiCore;
import com.cndw.kungfu.model.pvp.api.WarApiClient;
import com.cndw.kungfu.model.pvp.api.ApiConfig;
import com.cndw.kungfu.model.pvp.war.WarBet;
import com.cndw.kungfu.model.pvp.war.WarConfig;
import com.cndw.kungfu.model.pvp.war.WarCoreCenter;
import com.cndw.kungfu.model.pvp.war.WarData;
import com.cndw.kungfu.model.pvp.war.WarVs;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 华山论剑入口
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2012-7-20 下午8:34:22
 */
@Controller
public class WarController {

	@Autowired
	private IPlayerManager playerManager;

	public ResponseMessage show(Session session) {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cycleBegin", WarConfig.getSingleBegin());// 本季度开始时间
		map.put("applyEndTime", WarConfig.getSingleBegin() + WarConfig.applyTime);
		map.put("apply", WarData.getInstance().isApplay(session.getUid()));
		map.put("crossJoin", WarData.getInstance().isProm32(session.getUid()));
		map.put("stateWar", CrossProxySerialize.getInstance().getStateWar());
		map.put("cycle", WarConfig.getCycle());

		return ResponseMessage.getSuccMessage(map);
	}

	@LocalCommand
	public ResponseMessage test(Session session, int type) {
		if (type == 0) {
			List<Player> players = playerManager.getPlayers(0, null, null, 0, 0, 0, 0, 0, 1000);
			for (Player e : players) {
				int ranking = DataSerialize.getInstance().getChallengeData().getOrder(e.getPlayerId());
				if (ranking == 0) {
					DataSerialize.getInstance().getChallengeData().addOrder(e.getPlayerId());
				}
			}
			DataSerialize.getInstance().commitSync();
			CrossProxySerialize.getInstance().stateWar(0, 0, 0);
			CrossProxySerialize.getInstance().stateWar(1, 0, 0);

			WarData.getInstance().clear();
			if (ApiCore.isCrossServer()) {
				WarCrossAreaSerialize.clearCross();
			}
		} else if (type == 1) {
			CrossProxySerialize.getInstance().stateWar(1, 0, 0);
			if (ApiCore.isCrossServer()) {
				WarCoreCenter.getCrossData(1).clear();
				WarCrossAreaSerialize.clearCross();
			}

		} else if (type == 2) {
			CrossProxySerialize.getInstance().stateWar(2, 0, 0);
			if (ApiCore.isCrossServer()) {
				WarCoreCenter.getWarWorld().clear();
			}
		} else if (type == 9) {

			WarCoreCenter.chatMsssage(0, "测试.....  " + System.currentTimeMillis());

		}
		LogUtil.getMain().debug("up corss type " + type);
		CrossProxySerialize.getInstance().commitSync();
		return null;
	}

	/**
	 * 报名
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage apply(Session session) {
		if (WarData.getInstance().isApplay(session.getUid())) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < WarConfig.applyLevel) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("war.apply.level", WarConfig.applyLevel));
		}
		int curerentTime = TimeProcesser.getUnixTime();

		if (curerentTime < WarConfig.getSingleBegin() || curerentTime > WarConfig.getSingleBegin() + WarConfig.applyTime) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("war.apply.time"));
		}

		WarData.getInstance().applay(session.getUid());
		WarData.getInstance().commitSync();
		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 显示我的比赛信息
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage vs(Session session) {
		Iterator<WarVs> it = WarData.getInstance().getVsIterator();
		List<Object[]> vsList = new ArrayList<Object[]>();
		int diff = TimeProcesser.getUnixTime() - WarConfig.getSingleBegin() - WarConfig.eliminateBegin;
		int k = 0;
		while (it.hasNext()) {
			WarVs warVs = (WarVs) it.next();
			if (warVs == null) {
				continue;
			}
			long t = warVs.getS() == session.getUid() ? warVs.getT() : warVs.getT() == session.getUid() ? warVs.getS() : 0;
			if (t > 0) {
				Player target = Context.getPlayerServer().getByPlayerId(t);
				boolean win = warVs.getS() == session.getUid() ? warVs.getW() == 1 : warVs.getW() == 2;

				if (target != null) {
					vsList.add(new Object[] { target.getPlayerId(), target.getPlayerName(), warVs.getW() == 0 ? 0 : win ? 1 : 2 });
				}
				k++;
				if (diff <= k * WarConfig.emtOneTime) {
					break;
				}
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("vsList", vsList);
		map.put("emtNum", WarData.getInstance().getEmtNum(k));
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示晋级表
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage promotion(Session session) {
		Map<Integer, Map<Integer, Long>> winerMap = WarData.getInstance().getWinerMap();
		Map<Integer, Map<Integer, Object[]>> view = new HashMap<Integer, Map<Integer, Object[]>>();
		for (int i = 1; i < WarConfig.camTypeList.length; i++) {
			int cmType = WarConfig.camTypeList[i];
			if (winerMap.containsKey(cmType)) {
				HashMap<Integer, Object[]> camWiner = new HashMap<Integer, Object[]>();
				view.put(cmType, camWiner);
				Map<Integer, Long> erMap = winerMap.get(cmType);
				Iterator<Entry<Integer, Long>> it = erMap.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry<Integer, Long> entry = (Map.Entry<Integer, Long>) it.next();
					Player target = Context.getPlayerServer().getByPlayerId(entry.getValue());
					if (target == null) {
						LogUtil.getMain().debug("err xxxx" + entry.getValue());
					}
					camWiner.put(entry.getKey(),
							new Object[] { target.getPlayerId(), target.getPlayerName(), target.getVocationId(), target.getLevel(), target.getScore() });
				}
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("view", view);
		int camType = WarData.getInstance().getCamType();
		map.put("batOnceAsset", WarConfig.batOnceAsset.containsKey(camType) ? WarConfig.batOnceAsset.get(camType) : 0);

		WarBet warBet = WarData.getInstance().betGet(session.getUid());
		if (warBet != null && warBet.getC() <= camType) {
			map.put("betTarget", WarData.getInstance().betGet(session.getUid()));
			Player target = Context.getPlayerServer().getByPlayerId(warBet.getT());
			map.put("betName", target.getPlayerName());
		} else {
			// map.put("canBet", WarData.getInstance().isBet());
		}
		map.put("canBet", WarData.getInstance().isBet());

		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage promotionvs(Session session, long sourceId, long targetId) {
		Iterator<WarVs> it = WarData.getInstance().getOrderVsList();
		List<Object[]> vsList = new ArrayList<Object[]>();
		while (it.hasNext()) {
			WarVs warVs = (WarVs) it.next();
			if ((sourceId == warVs.getS() && targetId == warVs.getT()) || (sourceId == warVs.getT() && targetId == warVs.getS())) {
				Player source = Context.getPlayerServer().getByPlayerId(warVs.getS());
				Player target = Context.getPlayerServer().getByPlayerId(warVs.getT());
				if (source != null && target != null) {
					vsList.add(new Object[] { source.getPlayerId(), source.getPlayerName(), target.getPlayerId(), target.getPlayerName(), warVs.getW() });
				}
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("vsList", vsList);
		map.put("camType", WarData.getInstance().getCamType());
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage promotionMy(Session session) {
		Iterator<WarVs> it = WarData.getInstance().getOrderVsList();
		List<Object[]> vsList = new ArrayList<Object[]>();
		while (it.hasNext()) {
			WarVs warVs = (WarVs) it.next();

			long t = warVs.getS() == session.getUid() ? warVs.getT() : warVs.getT() == session.getUid() ? warVs.getS() : 0;
			if (t > 0) {
				Player target = Context.getPlayerServer().getByPlayerId(t);
				boolean win = warVs.getS() == session.getUid() ? warVs.getW() == 1 : warVs.getW() == 2;
				vsList.add(new Object[] { target.getPlayerId(), target.getPlayerName(), warVs.getW() == 0 ? 0 : win ? 1 : 2, warVs.getC() });
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("vsList", vsList);
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage bet(Session session, int camType, long targetId, int noteNums) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		int onceAsset = WarConfig.batOnceAsset.get(camType);

		if (noteNums > player.getLevel() || noteNums <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("war.bet.level", player.getLevel(), player.getLevel()));
		}
		int asset = noteNums * onceAsset;
		if (asset <= 0) {
			return null;
		}
		if (player.getAsset() < asset) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.asset"));
		}
		WarBet betOld = WarData.getInstance().betGet(session.getUid());
		if (betOld != null && betOld.getC() <= camType) {
			return null;
		}
		if (!WarData.getInstance().isBet()) {
			return null;
		}
		if (WarData.getInstance().getCamType() != camType) {
			return null;
		}

		player.alterAsset(-asset);
		WarData.getInstance().betAsset(camType, session.getUid(), targetId, asset);
		WarData.getInstance().commitSync();

		LogServer.recordLog(player, ConstantsLog.activity, 90301, noteNums, asset, targetId);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("asset", player.getAsset());
		map.put("betTarget", WarData.getInstance().betGet(session.getUid()));
		map.put("camType", camType);
		map.put("betName", Context.getPlayerServer().getByPlayerId(targetId).getPlayerName());
		map.put("canBet", WarData.getInstance().isBet());
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage betList(Session session) {
		Iterator<WarBet> bets = WarData.getInstance().getBets();
		List<Object[]> myBets = new ArrayList<Object[]>();
		while (bets.hasNext()) {
			WarBet warBet = (WarBet) bets.next();
			if (warBet.getS() == session.getUid()) {
				Player target = Context.getPlayerServer().getByPlayerId(warBet.getT());
				myBets.add(new Object[] { warBet.getC(), warBet.getT(), target.getPlayerName(), warBet.getAsset(), warBet.getW() });
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("bets", myBets);
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage flowersShow(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int flowerTimes = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.flower);
		int flowerTimes2 = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.flower2);
		int[] cost = new int[5];
		cost[0] = WarConfig.costIntNum[0];
		cost[1] = WarConfig.getCostByTimes(1, flowerTimes);
		cost[2] = WarConfig.getCostByTimes(2, flowerTimes);
		cost[3] = WarConfig.getCostByTimes(3, flowerTimes2);
		cost[4] = WarConfig.getCostByTimes(4, flowerTimes2);

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("flowerFree", !player.getDataInfo().getEveryDay().intDataStatContants(ConstantsDayIntKey.flowerF, 1));
		map.put("flowerFree2", !player.getDataInfo().getEveryDay().intDataStatContants(ConstantsDayIntKey.flowerF, 2));
		map.put("cost", cost);
		long t = CrossProxySerialize.getInstance().getSingleBoss();
		if (t > 0) {
			Player target = Context.getPlayerServer().getByPlayerId(t);
			map.put("bossId", target.getPlayerId());
			map.put("bossName", target.getPlayerName());
			map.put("bossVid", target.getVocationId());
			map.put("bossPp", target.getScore());

		}

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 献花的接口
	 * 
	 * @param session
	 * @param type
	 * @return
	 */
	public ResponseMessage flowers(Session session, int type, boolean cross) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int costAsset = 0, costGold = 0;
		if (type < 0 || type > 2) {
			return null;
		}
		if (!player.getPlayerBoxs().checkBlack()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", 1));
		}
		int flowerTimes = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.flower);
		int flowerTimes2 = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.flower2);
		int sign = cross ? 2 : 1;
		if (type == 0) {
			if (player.getDataInfo().getEveryDay().intDataStatContants(ConstantsDayIntKey.flowerF, sign)) {
				return null;
			}
			costAsset = 10000;
		} else {
			if (cross) {
				costGold = WarConfig.getCostByTimes(type + 2, flowerTimes2);
			} else {
				costGold = WarConfig.getCostByTimes(type, flowerTimes);
			}
		}
		if (costAsset > 0) {
			if (player.getAsset() < costAsset) {
				return null;
			}
			player.alterAsset(-costAsset);
		}
		if (costGold > 0) {
			if (player.getGoldAll() < costGold) {
				return null;
			}
			player.alterGoldAll(-costGold);
		}
		int heroNum = 0;
		if (type == 0) {
			Context.getGoodsServer().giveGoodsBing(session.getUid(), WarConfig.assetGoodsId, 1, 1);
			heroNum = NumberProcesser.isWinning(10) ? 1 : 0;
		} else {
			heroNum = type == 2 ? 5 : 1;
			heroNum = cross ? heroNum * 2 : heroNum;
		}
		if (heroNum > 0) {
			Context.getGoodsServer().giveGoodsBing(session.getUid(), WarConfig.heroGoodsId, heroNum, 1);
		}
		if (type == 0) {
			player.getDataInfo().getEveryDay().intDataBitStatAdd(ConstantsDayIntKey.flowerF, sign);
		} else {
			if (cross) {
				flowerTimes2++;
				player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.flower2, flowerTimes2);
				//TODO 记录问道次数  结束  11-20
				if (type == 2) {
					player.getDataInfo().getEveryDay().intDataAlter(ConstantsDayIntKey.twf, 1);
				}
			} else {
				flowerTimes++;
				player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.flower, flowerTimes);
			}
		}

		// 加到每日奖励
		player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.sendFlowerOrHallowItem);

		player.commitSync();
		player.getDataInfo().commitSync();
		LogServer.recordLog(player, ConstantsLog.activity, 90304, costAsset, costGold, heroNum, type, cross);
		if (costGold > 0) {
			LogServer.costEventLog(session.getUid(), costGold, ConstantsCost.warFlower);
		}
		if (!cross) {
			WarCoreCenter.flower(player.getPlayerId(), player.getPlayerName(), type, ConstantsConfig.getSysCgServiceId());
		} else if (type > 0) {//只有花费了的才上去
			WarCoreCenter.flowerCross(player.getPlayerId(), player.getPlayerName(), type);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("asset", player.getAsset());
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("type", type);
		map.put("heroNum", heroNum);

		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage flowerList(Session session, boolean cross) {
		if (cross) {
			return ResponseMessage.getSuccMessage(WarApiClient.getWarFlowers());
		} else {
			return ResponseMessage.getSuccMessage(CrossProxySerialize.getInstance().getWarFlowers());
		}
	}

	public ResponseMessage crossVs(Session session) {
		Map<String, Object> map = WarApiClient.getCrossVs(session.getUid());
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage crossPromotion(Session session) {
		Map<String, Object> map = WarApiClient.getCrossPromotion(session.getUid());
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage crossPromotionvs(Session session, long sourceId, long targetId) {
		Map<String, Object> map = WarApiClient.getCrossPromotionvs(sourceId, targetId);
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage crossPromotionMy(Session session) {
		Map<String, Object> map = WarApiClient.getCrossPromotionMy(session.getUid());
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage crossBet(Session session, int camType, long targetId, int noteNums) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		int onceAsset = WarConfig.batOnceAsset.get(camType);

		if (noteNums > player.getLevel() || noteNums <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("war.bet.level", player.getLevel(), player.getLevel()));
		}
		int asset = noteNums * onceAsset;
		if (asset <= 0) {
			return null;
		}
		if (player.getAsset() < asset) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.asset"));
		}

		Map<String, Object> msg = WarApiClient.getCrossBet(session.getUid(), camType, targetId, asset);
		boolean suc = msg != null && msg.containsKey("ret") && (Boolean) msg.get("ret");
		if (suc) {
			player.alterAsset(-asset);
			player.commitSync();
			LogServer.recordLog(player, ConstantsLog.activity, 90301, noteNums, asset, targetId);
		} else {

		}
		msg.put("asset", player.getAsset());
		msg.put("camType", camType);
		return ResponseMessage.getSuccMessage(msg);
	}

	public ResponseMessage crossBetList(Session session) {
		Map<String, Object> map = WarApiClient.getCrossBetList(session.getUid());
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage crossOrderPower(Session session) {
		Map<String, Object> map = WarApiClient.getCrossOrderPower();
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * =================================================== 天下第一分界线
	 * ===================================================
	 */

	public ResponseMessage worldVs(Session session) {
		return WarApiClient.worldApiResp(ApiConfig.worldVs, session.getUid());
	}

	public ResponseMessage worldPromotion(Session session) {
		return WarApiClient.worldApiResp(ApiConfig.worldPromotion, session.getUid());
	}

	public ResponseMessage worldPromotionvs(Session session, long sourceId, long targetId) {
		return WarApiClient.worldApiResp(ApiConfig.worldPromotionvs, sourceId, targetId);
	}

	public ResponseMessage worldPromotionMy(Session session) {
		return WarApiClient.worldApiResp(ApiConfig.worldPromotionMy, session.getUid());
	}

	public ResponseMessage worldBet(Session session, int camType, long targetId, int noteNums) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		int onceAsset = WarConfig.batOnceAsset.get(camType);

		if (noteNums > player.getLevel() || noteNums <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("war.bet.level", player.getLevel(), player.getLevel()));
		}
		int asset = noteNums * onceAsset;
		if (asset <= 0) {
			return null;
		}
		if (player.getAsset() < asset) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.asset"));
		}

		Map<String, Object> msg = WarApiClient.worldApiMap(ApiConfig.worldBet, ConstantsConfig.getSysCgServiceId(), session.getUid(), camType, targetId, asset);
		boolean suc = msg != null && msg.containsKey("ret") && (Boolean) msg.get("ret");
		if (suc) {
			player.alterAsset(-asset);
			player.commitSync();
			LogServer.recordLog(player, ConstantsLog.activity, 90301, noteNums, asset, targetId);
		} else {

		}
		msg.put("asset", player.getAsset());
		msg.put("camType", camType);
		return ResponseMessage.getSuccMessage(msg);
	}

	public ResponseMessage worldBetList(Session session) {
		return WarApiClient.worldApiResp(ApiConfig.worldBetList, session.getUid());
	}

	public ResponseMessage worldOrderPower(Session session) {
		return WarApiClient.worldApiResp(ApiConfig.worldOrderPower);
	}

}
